package cn.edu.jsu.official.service.serviceImpl;

import cn.edu.jsu.official.dao.AdminDao;
import cn.edu.jsu.official.pojo.dto.*;
import cn.edu.jsu.official.pojo.vo.*;
import cn.edu.jsu.official.service.AdminService;
import cn.edu.jsu.official.utils.CollectionUtil;
import cn.edu.jsu.official.authenticate.util.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.edu.jsu.official.utils.Word2Html.Word2HtmlConvert;


/**
 * @author Mo
 * @createTime 2022/3/2 23:09
 * @description
 */
@Slf4j
@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminDao adminDao;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public CommonResult login(LoginVO loginVO, HttpServletRequest httpServletRequest) {
        try {
//            UserInfo userInfo = new UserInfo();
//            userInfo.setUserAccount(loginVO.getUserAccount());
//            userInfo.setPassword(loginVO.getUserPassword());
//            userInfo.setUserName("网站管理员");
//            userInfo.setUserType(1);
//            mongoTemplate.insert(userInfo);
//            return null;
            int i = adminDao.queryAccount(loginVO.getUserAccount());
            if (i <= 0) {
                return new CommonResult(201, "账户未注册");
            }
            UserInfo userInfo = adminDao.queryAccountInfo(loginVO);
            LoginResponseVO loginResponseVO = new LoginResponseVO();
            if (userInfo != null) {
                loginResponseVO.setUserAccount(userInfo.getUserAccount());
                loginResponseVO.setUserType(userInfo.getUserType());
                loginResponseVO.setUserName(userInfo.getUserName());
                HashMap<String, String> payload = new HashMap<>();
                payload.put("userAccount", loginResponseVO.getUserAccount());
                String token = JWTUtil.getTOKEN(payload);
                loginResponseVO.setToken(token);
                System.out.println(token);
                return new CommonResult(200, "登陆成功", loginResponseVO);
            }
            return new CommonResult(202, "用户名或密码错误");
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(444, "错误");
        }
    }

    @Override
    public CommonResult uploadProjectAchievement(MultipartFile articleFile, MultipartFile frontCoverFile, ProjectAchievement projectAchievement) {
        String fileName = articleFile.getOriginalFilename();
        System.out.println(fileName);
        String suffix=fileName.substring(fileName.lastIndexOf("."));
        log.info("文件后缀为:" + suffix);
        if(suffix.equals(".docx")) {
            Map<String, String> stringMap = null;
            try {
                 stringMap = Word2HtmlConvert(articleFile);
            } catch (Exception e) {
                e.printStackTrace();
                return new CommonResult(444, "文件处理错误");
            }
            ArticleVO articleVO = new ArticleVO();
            assert stringMap != null;
            articleVO.setContent(stringMap.get("html"));
            articleVO.setResourcesPath(stringMap.get("resourcesPath"));
            ObjectId frontCoverId = adminDao.uploadFile(frontCoverFile);
            ArticleVO articleVO1 =  adminDao.insertArticle(articleVO);
            projectAchievement.setArticleId(new ObjectId(articleVO1.getArticleId()));
            projectAchievement.setFrontCoverId(frontCoverId);
            projectAchievement.setUploadDate(new Date());
            adminDao.addProjectAchievement(projectAchievement);
            return new CommonResult(200, "上传成功");
        } else {
            return new CommonResult(444, "非word docx文档,请检查文件格式");
        }
    }

    @Override
    public CommonResult addProjectInProgressInfo(MultipartFile frontCoverFile, ProjectInProgressInfo projectInProgressInfo) {
        ObjectId frontCoverId = adminDao.uploadFile(frontCoverFile);
        projectInProgressInfo.setFrontCoverId(frontCoverId);
        adminDao.addProjectInProgress(projectInProgressInfo);
        return new CommonResult(200, "添加成功");
    }

    @Override
    public CommonResult uploadContestAchievement(MultipartFile articleFile, MultipartFile frontCoverFile, ContestAchievement contestAchievement) {
        String fileName = articleFile.getOriginalFilename();
        String suffix=fileName.substring(fileName.lastIndexOf("."));
        if(suffix.equals(".doc") || suffix.equals(".docx")) {
            Map<String, String> stringMap = null;
            try {
                stringMap = Word2HtmlConvert(articleFile);
            } catch (Exception e) {
                e.printStackTrace();
                return new CommonResult(444, "文件处理错误");
            }
            ArticleVO articleVO = new ArticleVO();
            assert stringMap != null;
            articleVO.setContent(stringMap.get("html"));
            articleVO.setResourcesPath(stringMap.get("resourcesPath"));
            ArticleVO articleVO1 =  adminDao.insertArticle(articleVO);
            ObjectId frontCoverId = adminDao.uploadFile(frontCoverFile);

            contestAchievement.setUploadTime(new Date());
            contestAchievement.setFrontCoverId(frontCoverId);
            contestAchievement.setArticleId(new ObjectId(articleVO1.getArticleId()));
            adminDao.addContestAchievement(contestAchievement);
            return new CommonResult(200, "上传成功");
        } else {
            return new CommonResult(444, "非word文档,请检查文件格式");
        }
    }

    @Override
    public CommonResult uploadContestInfo(MultipartFile contestImage, ContestInfo contestInfo) {
        ObjectId imageId = adminDao.uploadFile(contestImage);
        contestInfo.setContestImageId(imageId);
        adminDao.addContestInfo(contestInfo);
        return new CommonResult(200, "上传成功");
    }

    @Override
    public CommonResult uploadCopyright(MultipartFile articleFile, MultipartFile frontCoverFile, CopyrightInfo copyrightInfo) {
        String fileName = articleFile.getOriginalFilename();
        String suffix=fileName.substring(fileName.lastIndexOf("."));
        if(suffix.equals(".doc") || suffix.equals(".docx")) {
            Map<String, String> stringMap = null;
            try {
                stringMap = Word2HtmlConvert(articleFile);
            } catch (Exception e) {
                e.printStackTrace();
                return new CommonResult(444, "文件处理错误");
            }
            ArticleVO articleVO = new ArticleVO();
            articleVO.setContent(stringMap.get("html"));
            articleVO.setResourcesPath(stringMap.get("resourcesPath"));
            ArticleVO articleVO1 =  adminDao.insertArticle(articleVO);
            ObjectId frontCoverId = adminDao.uploadFile(frontCoverFile);

            copyrightInfo.setArticleId(new ObjectId(articleVO1.getArticleId()));
            copyrightInfo.setFrontCoverId(frontCoverId);
            copyrightInfo.setUploadDate(new Date());
            adminDao.uploadCopyright(copyrightInfo);
            return new CommonResult(200, "上传成功");
        } else {
            return new CommonResult(444, "非word文档,请检查文件格式");
        }
    }

    @Override
    public CommonResult uploadMemberInfo(MultipartFile multipartFile, MemberInfo memberInfo) {
        ObjectId memberImageId = adminDao.uploadFile(multipartFile);
//        ObjectId memberImageId = new ObjectId();
        memberInfo.setMemberImageId(memberImageId);
        memberInfo.setIsShown(0);
        if(memberInfo.getIsGraduated()==0 || memberInfo.getIsGraduated() == null){
            memberInfo.setGraduationDestination("无");
        }
        adminDao.addMemberInfo(memberInfo);
        return new CommonResult(200, "上传成功");
    }

    @Override
    public CommonResult addGoalInfo(GoalInfo goalInfo) {
        adminDao.addGoalInfo(goalInfo);
        return new CommonResult(200, "上传成功");
    }

    @Override
    public CommonResult deleteProjectAchievement(List<String> projectAchievementIdList) {
        List<String> listWithoutNulls = CollectionUtil.listRemoveNullByParallel(projectAchievementIdList);
        if (listWithoutNulls.size() == 0) {
            return new CommonResult(444, "projectAchievementIdList为null");
        }

        List<Map<String, ObjectId>> mapList = adminDao.deleteProjectAchievementList(projectAchievementIdList);

        for (Map<String, ObjectId> map : mapList) {
            adminDao.deleteFile(map);
        }
        return new CommonResult(200, "删除成功");
    }

    @Override
    public CommonResult deleteProjectInProgress(List<String> projectIdList) {
        List<String> listWithoutNulls = CollectionUtil.listRemoveNullByParallel(projectIdList);
        if (listWithoutNulls.size() == 0) {
            return new CommonResult(444, "projectIdList为null");
        }
        System.out.println("传入的参数 ----" + projectIdList);
        adminDao.deleteProjectInProgress(projectIdList);
        return new CommonResult(200, "删除成功");
    }

    @Override
    public CommonResult deleteContestAchievement(List<String> contestAchievementIdList) {
        List<String> listWithoutNulls = CollectionUtil.listRemoveNullByParallel(contestAchievementIdList);
        if (listWithoutNulls.size() == 0) {
            return new CommonResult(444, "contestAchievementIdList为null");
        }
        List<Map<String, ObjectId>> mapList = adminDao.deleteContestAchievementList(listWithoutNulls);
        for (Map<String, ObjectId> map : mapList) {
            adminDao.deleteFile(map);
        }
        return new CommonResult(200, "删除成功");
    }

    @Override
    public CommonResult deleteContestInfo(List<String> contestInfoIdList) {
        List<String> listWithoutNulls = CollectionUtil.listRemoveNullByParallel(contestInfoIdList);
        if (listWithoutNulls.size() == 0) {
            return new CommonResult(444, "contestInfoIdList为null");
        }
        List<Map<String,ObjectId>> mapList=adminDao.deleteContestInfoList(listWithoutNulls);
        for(Map<String,ObjectId> map:mapList){
            adminDao.deleteFile(map);
        }
        return new CommonResult(200, "删除成功");
    }

    @Override
    public CommonResult deleteCopyright(List<String> copyrightIdList) {
        List<String> listWithoutNulls = CollectionUtil.listRemoveNullByParallel(copyrightIdList);
        if (listWithoutNulls.size() == 0) {
            return new CommonResult(444, "copyrightIdList为null");
        }
        List<Map<String,ObjectId>> mapList=adminDao.deleteCopyrightList(listWithoutNulls);
        for(Map<String,ObjectId> map:mapList){
            adminDao.deleteFile(map);
        }
        return new CommonResult(200, "删除成功");
    }

    @Override
    public CommonResult deleteMemberInfo(List<String> memberIdList) {
        List<String> listWithoutNulls = CollectionUtil.listRemoveNullByParallel(memberIdList);
        if (listWithoutNulls.size() == 0) {
            return new CommonResult(444, "memberIdList为null");
        }
        List<Map<String, ObjectId>> mapList = adminDao.deleteMemberIdList(listWithoutNulls);
        for (Map<String, ObjectId> map : mapList) {
            adminDao.deleteFile(map);
        }
        return new CommonResult(200, "删除成功");
    }

    @Override
    public CommonResult deleteGoalInfo(List<String> goalIdList) {
        if (goalIdList.size() != 0) {
            List<String> listWithoutNulls = CollectionUtil.listRemoveNullByParallel(goalIdList);
            if (listWithoutNulls.size() == 0) {
                return new CommonResult(444, "goalIdList为空");
            }
            adminDao.deleteGoalInfo(goalIdList);
            return new CommonResult(200, "删除成功");
        } else {
            return new CommonResult(444, "goalIdList为空");
        }

    }

    @Override
    public CommonResult countHonor() {
        long copyrightNumber = adminDao.countCopyright();
        long contestAchievementNumber = adminDao.countContestAchievement();
        long honorNumber = copyrightNumber + contestAchievementNumber;
        System.out.println("honorNumber: " + honorNumber);
        return new CommonResult(200, "查询成功", honorNumber);
    }

    @Override
    public CommonResult countMember() {
        long memberNumber = adminDao.countMember();
        return new CommonResult(200, "查询成功", memberNumber);
    }

    @Override
    public CommonResult countCopyright() {
        long copyrightNumber = adminDao.countCopyright();
        return new CommonResult(200, "查询成功", copyrightNumber);
    }

    @Override
    public CommonResult countContestAchievement() {
        long contestAchievementNumber = adminDao.countContestAchievement();
        return new CommonResult(200, "查询成功", contestAchievementNumber);
    }

    @Override
    public CommonResult countProjectAchievement() {
        long projectAchievementNumber = adminDao.countProjectAchievement();
        return new CommonResult(200, "查询成功", projectAchievementNumber);
    }
    @Override
    public CommonResult updateHistoryProcess(HistoryProcess historyProcess) {
        long i = adminDao.updateHistoryProcess(historyProcess);
        if (i > 0) {
            return new CommonResult(200, "修改成功!");
        } else {
            return new CommonResult(444, "修改失败!");
        }
    }

    @Override
    public CommonResult updateProjectAchievement(ProjectAchievement projectAchievement){
        long i = adminDao.updateProjectAchievement(projectAchievement);
        if (i > 0) {
            return new CommonResult(200, "修改成功!");
        } else {
            return new CommonResult(444, "修改失败!");
        }
    }

    @Override
    public CommonResult updateContestInfo(ContestInfo contestInfo) {
        long i = adminDao.updateContestInfo(contestInfo);
        if (i > 0) {
            return new CommonResult(200, "修改成功!");
        } else {
            return new CommonResult(444, "修改失败!");
        }
    }

    @Override
    public CommonResult updateGoalInfo(GoalInfo goalInfo) {
        long i = adminDao.updateGoalInfo(goalInfo);
        if (i > 0) {
            return new CommonResult(200, "修改成功!");
        } else {
            return new CommonResult(444, "修改失败!");
        }
    }

    @Override
    public CommonResult addHistoryProcess(HistoryProcess historyProcess) {
        adminDao.addHistoryProcess(historyProcess);
        return new CommonResult(200, "添加成功");
    }

    @Override
    public CommonResult deleteHistoryProcess(List<String> historyProcessIdList) {
        if (historyProcessIdList.size() != 0) {
            List<String> listWithoutNulls = CollectionUtil.listRemoveNullByParallel(historyProcessIdList);
            if (listWithoutNulls.size() == 0){
                return new CommonResult(444, "历史进程Id为空");
            }
            adminDao.deleteHistoryProcess(listWithoutNulls);
            return new CommonResult(200, "删除成功");
        } else {
            return new CommonResult(444, "历史进程Id为空");
        }
    }

    @Override
    public CommonResult updateProjectInProgress(ProjectInProgressInfo projectInProgressInfo) {
        int flag = adminDao.updateProjectInProgress(projectInProgressInfo);
        if (flag == 0) {
            return new CommonResult(444, "id异常");
        } else {
            return new CommonResult(200, "修改成功");
        }
    }

    @Override
    public CommonResult updatePassword(PwdInfo pwdInfo) {
        UserInfo equ = adminDao.queryPassword(pwdInfo.getUserInfo());
        if(equ != null){
            if(!equ.getPassword().equals(pwdInfo.getUserInfo().getPassword())) {
                return new CommonResult(444, "用户名或密码错误!");
            }
            UserInfo userInfo = new UserInfo();
            userInfo.setUserAccount(pwdInfo.getUserInfo().getUserAccount());
            userInfo.setPassword(pwdInfo.getPwd());
            long i = adminDao.updatePassword(userInfo);
            if (i > 0) {
                return new CommonResult(200, "修改成功!");
            } else {
                return new CommonResult(444, "修改失败!");
            }
        }
        return new CommonResult(444, "用户不存在！");
    }

    @Override
    public CommonResult updateContestAchievement(ContestAchievement contestAchievement) {
        int flag = adminDao.updateContestAchievement(contestAchievement);
        if (flag == 0) {
            return new CommonResult(444, "id异常");
        } else {
            return new CommonResult(200, "修改成功");
        }
    }

    @Override
    public CommonResult updateCopyright(CopyrightInfo copyrightInfo) {
        int flag = adminDao.updateCopyright(copyrightInfo);
        if (flag == 0) {
            return new CommonResult(444, "id异常");
        } else {
            return new CommonResult(200, "修改成功");
        }
    }

    @Override
    public CommonResult updateMemberInfo(MemberInfo memberInfo) {
        if (memberInfo.getMemberId() == null) {
            return new CommonResult(444, "memberId为空");
        }
        int flag = adminDao.updateMemberInfo(memberInfo);
        if (flag == 0) {
            return new CommonResult(444, "id异常");
        } else {
            return new CommonResult(200, "修改成功");
        }
    }

    @Override
    public CommonResult queryUserInfo(UserInfo userInfo) {
        // 不存在 or 为空则报错
        List<UserInfoVO> list = adminDao.queryUserInfo(userInfo);
        if (list.size() <= 0) {
            return new CommonResult(444, "查找不到用户!");
        }
        return new CommonResult(200, "查询成功!", list);
    }

    @Override
    public CommonResult chooseMemberToDisplay(MemberToShowVO memberToShowVO) {
        adminDao.updateMemberShownStatus(memberToShowVO);
        return new CommonResult(200, "修改成功");
    }

    @Override
    public CommonResult addTechStackInfo(TechStackInfo techStackInfo) {
        adminDao.addTechStackInfo(techStackInfo);
        return new CommonResult(200, "添加成功");
    }

    @Override
    public CommonResult deleteTechStackInfo(List<String> techStackInfoIdList) {
        if (techStackInfoIdList.isEmpty()) {
            return new CommonResult(444, "techStackInfoIdList 为 空");
        } else {
            List<String> listWithoutNulls = CollectionUtil.listRemoveNullByParallel(techStackInfoIdList);
            adminDao.deleteTechStackInfo(listWithoutNulls);
            return new CommonResult(200, "删除成功");
        }
    }

    @Override
    public CommonResult updateTechStackInfo(TechStackInfo techStackInfo) {
        if (techStackInfo == null) {
            return new CommonResult(444, "数据为空");
        } else {
            adminDao.updateTechStackInfo(techStackInfo);
            return new CommonResult(200, "修改成功");
        }
    }

    @Override
    public CommonResult updateArticle(String articleId, String articleContent){
        if(articleId ==null){
            return new CommonResult(444, "该文章不存在");
        }
        adminDao.updateArticle(articleId,articleContent);
        return new CommonResult(200, "修改成功");
    }

    @Override
    public CommonResult updateAvatar(MultipartFile avartar, String memberId) {
        MemberInfo memberInfo = adminDao.queryMemberById(memberId);
        if (memberInfo == null) {
            return new CommonResult(444, "查无此人");
        }
        Map<String, ObjectId> map = new HashMap<>();
        map.put("memberImageId", memberInfo.getMemberImageId());
        adminDao.deleteFile(map);
        ObjectId memberImageId = adminDao.uploadFile(avartar);
        memberInfo.setMemberImageId(memberImageId);
        adminDao.updateMemberInfo(memberInfo);
        return new CommonResult(200, "修改成功");
    }
}
